#!/usr/bin/env python
"""
调试搜索功能
"""

import os
import sys
import django

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
django.setup()

from django.contrib.auth.models import User, Group, Permission
from django.contrib.contenttypes.models import ContentType
from apps.permissions.models import GroupProfile


def debug_search():
    """调试搜索功能"""
    print("🔍 调试搜索功能")
    
    # 获取测试组
    try:
        group = Group.objects.get(name='TestGroup')
        print(f"✅ 找到测试组: {group.name}")
    except Group.DoesNotExist:
        print("❌ 测试组不存在")
        return
    
    # 获取组权限
    permissions = group.permissions.all().select_related('content_type')
    print(f"📋 组权限总数: {permissions.count()}")
    
    # 显示所有权限
    for perm in permissions:
        print(f"   - {perm.codename} | {perm.name} | {perm.content_type.app_label}.{perm.content_type.model}")
    
    # 测试搜索
    search_term = "user"
    print(f"\n🔍 搜索关键词: '{search_term}'")
    
    # 手动构建搜索查询
    from django.db.models import Q
    search_fields = ['name', 'codename', 'content_type__model']
    
    search_queries = Q()
    for field in search_fields:
        search_queries |= Q(**{f"{field}__icontains": search_term})
        print(f"   添加搜索条件: {field}__icontains={search_term}")
    
    # 执行搜索
    try:
        filtered_permissions = permissions.filter(search_queries)
        print(f"✅ 搜索结果数量: {filtered_permissions.count()}")
        
        for perm in filtered_permissions:
            print(f"   - 匹配: {perm.codename} | {perm.name} | {perm.content_type.app_label}.{perm.content_type.model}")
    
    except Exception as e:
        print(f"❌ 搜索失败: {e}")
        import traceback
        traceback.print_exc()
    
    # 测试配置式搜索
    print(f"\n🧪 测试配置式搜索")
    from apps.permissions.views import GroupViewSet
    from django.test import RequestFactory
    
    # 创建模拟请求
    factory = RequestFactory()
    request = factory.get(f'/test/?search={search_term}')
    
    # 创建ViewSet实例
    viewset = GroupViewSet()
    viewset.request = request
    
    try:
        # 获取Action配置
        config = viewset.get_action_config('permissions')
        print(f"📋 Action配置: {config}")
        
        # 应用过滤
        filtered_queryset = viewset.apply_action_filters(permissions, request, config)
        print(f"✅ 配置式搜索结果数量: {filtered_queryset.count()}")
        
        for perm in filtered_queryset:
            print(f"   - 配置式匹配: {perm.codename} | {perm.name}")
    
    except Exception as e:
        print(f"❌ 配置式搜索失败: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    debug_search()
